<template>
  <div id="labChannel">
    <Splitpanes horizontal class="horizontalLine">
      <Pane size="40">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">仪器列表</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="loading" @click="findChannelList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="handleAdd"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="handleSave" :loading="saveLoading"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="数据同步" :loading="showDataLoading" @click="pullChannel"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBody">
          <vxe-table ref="labInstrSetupTable" border align="center" class="mytable-scrollbar" height="auto" :data="instrSetupList" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
              isArrow: true,
              isTab: true,
              isEdit: true
            }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source @current-change="rowClick" v-loading="loading">
            <vxe-column field="instrName" title="仪器名称"></vxe-column>
            <vxe-column field="instrIdNo" title="仪器ID" width="60"></vxe-column>
            <vxe-column field="instrCode" title="仪器代号"></vxe-column>
            <vxe-column field="reportGroupName" title="所属报告单元"></vxe-column>
            <vxe-column field="instrCalled" title="仪器简介"></vxe-column>
            <vxe-column field="instrMark" title="仪器型号"></vxe-column>
            <vxe-column field="instrClass" title="仪器类别"></vxe-column>
            <vxe-column field="instrRegister" title="仪器注册码"></vxe-column>
          </vxe-table>
        </div>
      </Pane>
      <Pane size="60">
        <div class="toolbartitle">通道号列表</div>
        <div class="tableBody2">
          <vxe-table ref="labChannelTable" v-loading="loading" :row-config="{ isCurrent: true, isHover: true }" :data="channeList" border style="width: 100%" height="auto" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @current-change="rowChanneClick" resizable show-overflow keep-source :column-config="{ resizable: true }">
            <vxe-column field="seq" title="序号" width="30" type="seq" align="center"></vxe-column>

            <vxe-column field="channelCode" title="通道号" width="100" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.channelCode }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.channelCode" placeholder="请输入通道号" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column field="itemDictId" title="对应报告项目" width="100" align="center">
              <template #default="{ row }">
                <div>{{ row.itemDictName }}</div>
              </template>
            </vxe-column>
            <vxe-column field="isSplit" width="80" title="是否拆分开用" align="center">
              <template #default="{ row }">
                <vxe-switch v-model="row.isSplit" size="mini" open-label="是" close-label="否" open-value="1" close-value="0" @change="SwitchChangeIsSplit(row)"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="isSend" width="80" title="是否用于发送" align="center">
              <template #default="{ row }">
                <vxe-switch v-model="row.isSend" size="mini" open-label="是" close-label="否" open-value="1" close-value="0" @change="SwitchChangeIsSend(row)"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="isOpen" width="80" title="是否双工" align="center">
              <template #default="{ row }">
                <vxe-switch v-model="row.isOpen" size="mini" open-label="是" close-label="否" open-value="1" close-value="0" @change="SwitchChangeIsOpen(row)"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="isStop" title="是否停用" align="center" width="80">
              <template #default="{ row }">
                <vxe-switch v-model="row.isStop" size="mini" open-label="是" close-label="否" open-value="1" close-value="0" style="width: 100%"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="adjCoefficient" title="调整系数" width="100" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.adjCoefficient }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.adjCoefficient" placeholder="请输入调整系数" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="adjDiffer" title="调整差值" width="100" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.adjDiffer }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.adjDiffer" placeholder="请输入调整差值" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="testFun" title="测试方法" width="100" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.testFun }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.testFun" placeholder="请输入测试方法" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column field="resultMutual" width="100" title="结果互认" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.resultMutual }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.resultMutual" placeholder="请输入调整差值" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="lastUseDate" width="100" title="最后使用时间" align="center">
              <template #default="{ row }">
                <div>{{ row.lastUseDate }}</div>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { ref, reactive, onMounted, getCurrentInstance, watch, defineProps } from 'vue';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
import { Splitpanes, Pane } from 'splitpanes';
import { IsEmpty } from '@/utils/common';
import LogInfo from '@/components/LogInfo.vue';

// 全局变量定义区 ==========
let props = defineProps({
  form: {}, //表单
  itemClassDict: Array as () => String[], //项目归类字段
  instrClassDict: Array as () => String[], //仪器大类字典
  reportGroupDict: Array as () => String[], //报告单元字典
  itemKindDict: Array as () => String[], //结果类型字典
  rptGroup: String
}) as any;
// 方法定义区 =============
defineExpose({ ChannelInitPage });
let store = AppStore();
let showLoading = ref(false);
let { proxy }: any = getCurrentInstance();
let saveLoading = ref(false); //保存
let showDataLoading = ref(false);

// 方法定义区 =============
onMounted(() => {
  // findLabInstrSetupList();
  findChannelList();
});
let instrSetupList = reactive([]);
let loading = ref(false);
let itemNo = '';
let itemDictName = '';
let instrCode = '';
let channeList = reactive([]);

let rptGroup = '';

function SwitchChangeIsSplit(row) {
  if (row.isSplit === '0') {
    row.isOpen = '0';
  }
  if (row.isSplit === '1' && row.isSend === '1') {
    row.isOpen = '1';
  }
}
function SwitchChangeIsSend(row) {
  if (row.isSend === '0') {
    row.isOpen = '0';
  }
  if (row.isSplit === '1' && row.isSend === '1') {
    row.isOpen = '1';
  }
}

function SwitchChangeIsOpen(row) {
  if (row.isOpen === '1') {
    row.isSplit = '1';
    row.isSend = '1';
  }
}
//下拉选择报告单元与点击报告项目触发
function ChannelInitPage(refChannelData: any) {
  rptGroup = refChannelData.rptGroup;
  if (!IsEmpty(refChannelData)) {
    if (!IsEmpty(refChannelData.rptGroup)) {
      rptGroup = refChannelData.rptGroup;
    }
    if (!IsEmpty(refChannelData.itemDictRow)) {
      itemDictName = refChannelData.itemDictRow.value.itemName;
      itemNo = refChannelData.itemDictRow.value.itemNo;
    }
  }
  if (!IsEmpty(rptGroup)) {
    findLabInstrSetupList();
  }
}

function findLabInstrSetupList() {
  if (IsEmpty(rptGroup)) {
    instrSetupList.length = 0;
    return;
  }
  instrSetupList.length = 0;
  loading.value = true;
  const url = '/lis/instrSetup/findLabInstrSetupList';
  proxy.$http
    .get(url, { params: { rptGroupId: rptGroup } })
    .then((res: any) => {
      instrSetupList.length = 0;
      if (res.status.code === 1) {
        Object.assign(instrSetupList, res.data);
        //instrSetupList.push(...res.data);
        if (instrSetupList.length > 0) {
          rowClick({
            row: instrSetupList[0],
            rowIndex: 0
          });
        }
      }
      loading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      loading.value = false;
    });
}

function findChannelList() {
  channeList.length = 0;
  if (IsEmpty(rptGroup)) {
    return;
  }
  loading.value = true;
  const url = '/lab/channel/findChannelList';
  proxy.$http
    .get(url, { params: { itemNo: itemNo, instrCode: instrCode, rptGroup: rptGroup } })
    .then((res: any) => {
      channeList.length = 0;
      if (res.status.code === 200) {
        channeList.push(...res.data);
        if (channeList.length > 0) {
          rowChanneClick({
            row: channeList[0],
            rowIndex: 0
          });
        }
      }
      loading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      loading.value = false;
    });
}

let rowdata = {}; //点击当前行的数据
let rowIndexClick = 0; //点击当前行下标
// 点击仪器当前行
function rowClick({ row, rowIndex }: any) {
  rowIndexClick = rowIndex;
  rowdata = row;
  loading.value = false;
  const $labInstrSetupTable = proxy.$refs.labInstrSetupTable;
  if ($labInstrSetupTable) {
    $labInstrSetupTable.setCurrentRow(row);
  }
  instrCode = row.instrCode;
  findChannelList();
}

//点击通道号列表
function rowChanneClick({ row, rowIndex }: any) {
  rowIndexClick = rowIndex;
  rowdata = row;
  loading.value = false;
  const $labChannelTable = proxy.$refs.labChannelTable;
  if ($labChannelTable) {
    $labChannelTable.setCurrentRow(row);
  }
}

//删除参考范围信息
function handleDelete() {
  if (rowdata.id === '') {
    //没有做存储时，直接删除当前新增的列
    channeList.splice(rowdata.seq - 1, 1);
    return;
  }
  //凡是存储到库中的数据则需要清除库中的数据
  proxy.$http
    .post('/lab/channel/deleteChanne', { id: rowdata.id, channelCode: rowdata.channelCode })
    .then((res: any) => {
      if (res.status.code === 1) {
        findChannelList();
        VxeMessage('删除成功', VxeNotifyType.success);
      } else {
        return;
      }
    })
    .catch((err: any) => {
      VxeMessage('删除异常', VxeNotifyType.error);
    });
}

// 新增参考范围
function handleAdd() {
  if (IsEmpty(rptGroup)) {
    VxeMessage('请在左侧选择报告单元,并点击查询执行该操作', VxeNotifyType.error);
    return;
  }
  channeList.push({
    id: '',
    seq: channeList.length + 1,
    channelCode: '',
    itemNo: itemNo,
    instrCode: instrCode,
    isOpen: '0',
    adjCoefficient: '1.00000',
    adjDiffer: '0.0',
    testFun: '',
    resultMutual: '',
    isStop: '0',
    lastUseDate: '',
    isSplit: '0',
    isSend: '0',
    rptGroup: rptGroup,
    itemDictName: itemDictName
  });
}

let labChannelTable = ref();
// 点击修改新增保存
async function handleSave() {
  if (channeList.length === 0) {
    VxeMessage('务必先新增通道号-----点击【新增】设置通道号信息》》保存', VxeNotifyType.error);
    return;
  }

  let isAdjNull = false;
  channeList.forEach((m) => {
    if (IsEmpty(m.adjDiffer) || IsEmpty(m.adjCoefficient)) {
      isAdjNull = true;
    }
  });
  if (isAdjNull) {
    VxeMessage('存在调整系数/调整差值 为空的数据', VxeNotifyType.error);
    return;
  }
  saveLoading.value = true;
  // 获取表格实例
  const $Xtable = labChannelTable.value;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((item) => item.id !== '');

    // 拿到列表中id为空的为新增
    const InsertRecords = channeList.filter((item) => item.id === '');
    console.log('InsertRecords', InsertRecords);
    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let itemDictReferAddParam = e;
      proxy.$http
        .post('/lab/channel/editLabChannel', itemDictReferAddParam)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    });

    //新增参考范围
    InsertRecords.forEach((e: any) => {
      proxy.$http
        .post('/lab/channel/addLabChannel', e)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('创建成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('创建异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findChannelList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}
async function pullChannel() {
  showDataLoading.value = true;
  const url = '/api/sys/hisEmployee/getInterfaceData';
  const params = {
    url: '/labChannel/getlabChannel',
    code: 'GET_DICT_ITEM_CHANNEL'
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      VxeMessage('同步成功', VxeNotifyType.success);
      showDataLoading.value = false;
      findChannelList();
    })
    .catch((err: any) => {
      showDataLoading.value = false;
      VxeMessage('同步失败', VxeNotifyType.error);
    });
}
</script>
<style lang="scss" scoped>
#labChannel {
  width: 100%;
  height: 100%;

  .horizontalLine {
    :deep(.splitpanes__splitter) {
      background-color: $base-white;
    }
  }

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  .tableBody {
    height: calc(100% - 40px);
  }

  .tableBody2 {
    height: calc(100% - 45px);
  }
}
</style>
